package pl.grabar.clinic.client.web.actions.reception.patient;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import pl.grabar.clinic.core.dao.Dao;
import pl.grabar.clinic.core.domain.person.Patient;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@Action("edit")
@InterceptorRef("grabarStack")
@Results({ @Result(name = "success", location = "edit.jsp"), @Result(name = "input", type = "redirectAction", location = "list") })
public class EditPatientAction extends ActionSupport implements Preparable {

	private static final long serialVersionUID = 490605937484766091L;

	private static final Log LOG = LogFactory.getLog(EditPatientAction.class);

	@Autowired
	private Dao<Patient> patientDao;

	private String patientId;

	private Patient patient;

	private Patient existingPatient;

	@Override
	public void prepare() throws Exception {
		if (StringUtils.isNotBlank(patientId) && NumberUtils.isNumber(patientId)) {
			existingPatient = patientDao.findById(patientId);
			patient = existingPatient;
		}
		System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(patient));
	}

	@Override
	public void validate() {
		if (!hasErrors()) {
			if (existingPatient == null) {
				addActionError(getText("pl.grabar.clinic.client.web.reception.patient.actions.no-such-group"));
				LOG.error("Blad walidacji w trakcie edycji pacjenta. Pacjent o podanym id nie istnieje: " + patientId);
			}
		}
	}

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}

	/* AKCESORY */

	public void setPatientDao(Dao<Patient> patientDao) {
		this.patientDao = patientDao;
	}

	public String getPatientId() {
		return patientId;
	}

	public void setPatientId(String patientId) {
		this.patientId = patientId;
	}

	public Patient getPatient() {
		return patient;
	}

	public void setPatient(Patient patient) {
		this.patient = patient;
	}

	public Patient getExistingPatient() {
		return existingPatient;
	}

	public void setExistingPatient(Patient existingPatient) {
		this.existingPatient = existingPatient;
	}

}
